package apis

import (
	"fmt"
	"ginchat/internal/globals"
	"ginchat/internal/rpcServer"
	"ginchat/internal/settings"
	"ginchat/utils/errorx"
	"ginchat/utils/message"
	"time"

	"github.com/spf13/viper"
)

func StartHttp() {
	defer globals.GetWaitGroup().Done()

	err := settings.InitDataBase()
	if err != nil {
		errorx.ErrorExit(err)
		return
	}

	message.Println("The database initialize successfully.")

	go rpcServer.StartRPCServers()

	go func() {
		engine := settings.InitGinEngine()
		dst := fmt.Sprintf(
			"%s:%s",
			viper.GetString("system.host"),
			viper.GetString("system.port"),
		)

		err = engine.Run(dst)
		if err != nil {
			errorx.ErrorExit(err)
		}
	}()

	time.Sleep(3 * time.Second)
	message.Println("service is up...")
}
